const cityOptions = {
    '福建': ['福州', '厦门', '泉州', '莆田', '三明', '南平', '龙岩', '宁德', '漳州'],
    '广东': ['广州', '深圳', '珠海', '汕头', '韶关', '佛山', '江门', '湛江', '茂名', '肇庆', '惠州', '梅州', '汕尾', '河源', '阳江', '清远', '东莞', '中山', '潮州', '揭阳', '云浮']
};

const districtOptions = {
    '福州': ['鼓楼区', '台江区', '仓山区', '马尾区', '晋安区', '长乐区', '福清市', '闽侯县', '连江县', '罗源县', '闽清县', '永泰县', '平潭县'],
    '厦门': ['思明区', '海沧区', '湖里区', '集美区', '同安区', '翔安区'],
    '泉州': ['鲤城区', '丰泽区', '洛江区', '泉港区', '石狮市', '晋江市', '南安市', '惠安县', '安溪县', '永春县', '德化县', '金门县'],
    '莆田': ['城厢区', '涵江区', '荔城区', '秀屿区', '仙游县'],
    '三明': ['梅列区', '三元区', '永安市', '明溪县', '清流县', '宁化县', '大田县', '尤溪县', '沙县', '将乐县', '泰宁县', '建宁县'],
    '南平': ['延平区', '建阳区', '邵武市', '武夷山市', '建瓯市', '顺昌县', '浦城县', '光泽县', '松溪县', '政和县'],
    '龙岩': ['新罗区', '永定区', '漳平市', '长汀县', '上杭县', '武平县', '连城县'],
    '宁德': ['蕉城区', '福安市', '福鼎市', '寿宁县', '霞浦县', '柘荣县', '屏南县', '古田县', '周宁县'],
    '漳州': ['芗城区', '龙文区', '龙海市', '云霄县', '漳浦县', '诏安县', '长泰县', '东山县', '南靖县', '平和县', '华安县'],
    '广州': ['天河区', '越秀区', '海珠区', '荔湾区', '白云区', '黄埔区', '番禺区', '花都区', '南沙区', '从化区', '增城区'],
    '深圳': ['南山区', '福田区', '罗湖区', '盐田区', '宝安区', '龙岗区', '龙华区', '坪山区', '光明区', '大鹏新区'],
    '珠海': ['香洲区', '斗门区', '金湾区'],
    '汕头': ['龙湖区', '金平区', '濠江区', '潮阳区', '潮南区', '澄海区', '南澳县'],
    '韶关': ['武江区', '浈江区', '曲江区', '乐昌市', '南雄市', '始兴县', '仁化县', '翁源县', '新丰县', '乳源瑶族自治县'],
    '佛山': ['禅城区', '南海区', '顺德区', '三水区', '高明区'],
    '江门': ['蓬江区', '江海区', '新会区', '台山市', '开平市', '鹤山市', '恩平市'],
    '湛江': ['赤坎区', '霞山区', '坡头区', '麻章区', '廉江市', '雷州市', '吴川市', '遂溪县', '徐闻县'],
    '茂名': ['茂南区', '电白区', '高州市', '化州市', '信宜市'],
    '肇庆': ['端州区', '鼎湖区', '高要区', '四会市', '广宁县', '怀集县', '封开县', '德庆县'],
    '惠州': ['惠城区', '惠阳区', '博罗县', '惠东县', '龙门县'],
    '梅州': ['梅江区', '梅县区', '兴宁市', '大埔县', '丰顺县', '五华县', '平远县', '蕉岭县'],
    '汕尾': ['城区', '海丰县', '陆河县', '陆丰市'],
    '河源': ['源城区', '紫金县', '龙川县', '连平县', '和平县', '东源县'],
    '阳江': ['江城区', '阳东区', '阳西县', '阳春市'],
    '清远': ['清城区', '清新区', '英德市', '连州市', '佛冈县', '阳山县', '连山壮族瑶族自治县', '连南瑶族自治县'],
    '东莞': ['莞城区', '南城区', '东城区', '万江区', '石碣镇', '石龙镇', '茶山镇', '石排镇', '企石镇', '横沥镇', '桥头镇', '谢岗镇', '东坑镇', '常平镇', '寮步镇', '大朗镇', '黄江镇', '清溪镇', '塘厦镇', '凤岗镇', '大岭山镇', '长安镇', '虎门镇', '厚街镇', '沙田镇', '道滘镇', '洪梅镇', '麻涌镇', '中堂镇', '高埗镇'],
    '中山': ['石岐区', '东区', '西区', '南区', '五桂山区', '火炬开发区', '黄圃镇', '南头镇', '东凤镇', '阜沙镇', '小榄镇', '东升镇', '古镇镇', '横栏镇', '三角镇', '民众镇', '南朗镇', '港口镇', '大涌镇', '沙溪镇', '三乡镇', '板芙镇', '神湾镇', '坦洲镇'],
    '潮州': ['湘桥区', '潮安区', '饶平县'],
    '揭阳': ['榕城区', '揭东区', '揭西县', '惠来县', '普宁市'],
    '云浮': ['云城区', '云安区', '新兴县', '郁南县', '罗定市']
};

// 本来想要全国的，但是感觉实在太长了，就只写了两个省份的

// 显示地址选择弹窗
function showManageAddress() {
    document.getElementById('manage-address-popup').style.display = 'block';
    getAddress();
}

// 显示添加地址弹窗
function showAddAddress() {
    document.getElementById('add-address-popup').style.display = 'block';
}

// 关闭弹窗
function closePopup(popupId) {
    document.getElementById(popupId).style.display = 'none';
}

// 更新城市信息
function updateCityOptions() {
    const province = document.getElementById('province-select').value;
    const citySelect = document.getElementById('city-select');
    citySelect.innerHTML = '<option value="" disabled selected>选择城市</option>';

    cityOptions[province].forEach(city => {
        const option = document.createElement('option');
        option.value = city;
        option.textContent = city;
        citySelect.appendChild(option);
    });
}

// 更新区县信息
function updateDistrictOptions() {
    const city = document.getElementById('city-select').value;
    const districtSelect = document.getElementById('district-select');
    districtSelect.innerHTML = '<option value="" disabled selected>选择区县</option>';

    if (districtOptions[city]) {
        districtOptions[city].forEach(district => {
            const option = document.createElement('option');
            option.value = district;
            option.textContent = district;
            districtSelect.appendChild(option);
        });
    }
}


let fullName;
let gender;
let phoneNumber;
let province;
let city;
let district;
let fullAddress;
let address ;
let oldAddress;

// 添加地址
function addAddress() {
    fullName = document.getElementById('full-name').value;
    gender = document.getElementById('gender-select').value;
    phoneNumber = document.getElementById('phone-number').value;
    province = document.getElementById('province-select').value;
    city = document.getElementById('city-select').value;
    district = document.getElementById('district-select').value;
    fullAddress = document.getElementById('full-address').value;
    address = `${fullName} ${gender} - ${phoneNumber} - ${province} ${city} ${district} ${fullAddress}`;
    $.ajax({
        url:"/address",
        type:"GET",
        data:{type:"insert",address:address,userId:sessionStorage.getItem("userid")},
        success:function(data){
            if(data === "success"){
                showInfo("添加成功");
                getAddress();
            }
        }
    })
    closePopup('add-address-popup');
}

// 删除地址
function deleteAddress(button) {
    // 获取所点击按钮所在的卡片
    const card = button.closest('.card');
    // 获取地址信息
    let address = card.querySelector('div').textContent;
    address = address.split("：");
    $.ajax({
        url: "/address",
        type: "GET",
        data: {type: "delete", address: address[1], userId: sessionStorage.getItem("userid")},
        success: function (data) {
            if (data === "success") {
                showInfo("删除成功");
                getAddress();
            }
        }
    })
}

// 更新地址
function updateAddress() {
    fullName = document.getElementById('full-name').value;
    gender = document.getElementById('gender-select').value;
    phoneNumber = document.getElementById('phone-number').value;
    province = document.getElementById('province-select').value;
    city = document.getElementById('city-select').value;
    district = document.getElementById('district-select').value;
    fullAddress = document.getElementById('full-address').value;
    address = `${fullName} ${gender} - ${phoneNumber} - ${province} ${city} ${district} ${fullAddress}`;
    $.ajax({
        url:"/address",
        type:"GET",
        data:{type:"update",oldAddress:oldAddress,address:address,userId:sessionStorage.getItem("userid")},
        success:function(data){
            if(data === "success") {
                showInfo("修改成功");
                getAddress();
            }
        }
    })
}

// 获取所有地址
function getAddress(){
    $.ajax({
        url:"/address",
        type:"GET",
        data:{type:"get",address:"111",userId:sessionStorage.getItem("userid")},
        dataType:"json",
        success:function(dataString){
            const data = JSON.parse(dataString);
            document.getElementById('address').innerHTML = '';
            for(let i = 0; i < data.length; i++){
                const address = data[i];
                const card = document.createElement('div');
                card.className = 'card';
                card.innerHTML = `
                    <div>地址${i}：${address}</div>
                    <div class="address-actions">
                        <button onclick="editAddress(this)">修改</button>
                        <button onclick="deleteAddress(this)">删除</button>
                    </div>
                `;
                document.getElementById('address').appendChild(card);
                card.onclick = function() {
                    document.getElementById('address-bar').innerText = address;
                    closePopup('manage-address-popup');
                };
            }
        }
    })
}

// 编辑地址
function editAddress(button) {
    // 获取所点击按钮所在的卡片
    const card = button.closest('.card');
    const addBtn = document.getElementById('add');
    addBtn.onclick = updateAddress;
    // 获取地址信息
    const address = card.querySelector('div').textContent;
    populateAddress(address);
    showAddAddress();
}

// 拆分地址到弹窗界面
function populateAddress(addressString) {
    // 拆分字符串
    oldAddress = addressString.split("：")[1];
    const parts = addressString.split(" - ");
    const prefixAndName = parts[0].split("：");
    const prefix = prefixAndName[0];
    const fullNameAndGender = prefixAndName[1].split(" ");
    fullName = fullNameAndGender[0];
    gender = fullNameAndGender[1];
    phoneNumber = parts[1];
    const addressParts = parts[2].split(" ");
    province = addressParts[0];
    city = addressParts[1];
    district = addressParts[2];
    fullAddress = addressParts.slice(3).join(" ");
    // 填充字段
    document.getElementById('full-name').value = fullName;
    document.getElementById('gender-select').value = gender;
    document.getElementById('phone-number').value = phoneNumber;
    document.getElementById('province-select').value = province;
    updateCityOptions(); // 更新城市选项
    document.getElementById('city-select').value = city;
    updateDistrictOptions(); // 更新区县选项
    document.getElementById('district-select').value = district;
    document.getElementById('full-address').value = fullAddress;
}